'use strict';
const db = uniCloud.database()
const $ = db.command.aggregate
const dbCmd = db.command
exports.main = async (event, context) => {
	const {
		user_id, //用户_id
		article_id, //文章_id
		content, //评论内容
		comment_id='', //评论id
		reply_id='',	//子回复id
		is_reply=false  //是否子回复
	} = event

	//获取用户信息
	let userinfo = await db.collection('user').doc(user_id).get()
	userinfo = userinfo.data[0]
		
	//获取当前的文章信息
	const article=await db.collection('article').doc(article_id).get()	
	//获取文章下所有评论
	const comments=article.data[0].comments 
		
	//评论
	let commentObj = {
		comment_id: getID(6), //评论id
		comment_content: content, //	评论内容
		create_time: new Date().getTime(), //创建时间
		is_reply:is_reply,		//区分主回复,还是子回复
		author: {
			author_id: user_id, //作者id
			author_name: userinfo.author_name, //作者名称
			avatar: userinfo.avatar, //作者头像
			professional: userinfo.professional //作者专业			
		},
		replys: [] //回复
	}
 
	//if评论文章else回复文章评论
	if(comment_id===''){
		//评论文章
		commentObj.replys=[]	//清空回复
		commentObj=dbCmd.unshift(commentObj)		
	}else{
		//回复评论
		
		//获取评论索引
		let commentIndex=comments.findIndex(c=>c.comment_id===comment_id)
		
		let commentAuthor=''
		if(is_reply){
			//子回复	
			//获取作者信息
			commentAuthor=comments[commentIndex].replys.find(c=>c.comment_id=reply_id)
			commentAuthor=commentAuthor.author.author_name 
		}else{
			//主回复
			//获取作者信息
			commentAuthor=comments.find(c=>c.comment_id===comment_id)
			commentAuthor=commentAuthor.author.author_name 
		}
		 commentObj.to=commentAuthor
		 
		//更新回复信息
		commentObj={
			[commentIndex]:{
				replys:dbCmd.unshift(commentObj)	
			}
		}
	}
	 
	await db.collection('article').doc(article_id).update({
		comments: commentObj
	})

	//返回数据给客户端
	return {
		code: 200,
		msg: "评论成功"
	}
};

function getID(length) {
	return Number(Math.random().toString().substring(3, length) + Date.now()).toString()
}
